package com.bite.friend.service.user.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.bite.common.core.contants.Constants;
import com.bite.common.core.domain.PageQueryDTO;
import com.bite.common.core.domain.TableDataInfo;
import com.bite.common.core.utils.ThreadLocalUtil;
import com.bite.friend.domain.message.vo.MessageTextVO;
import com.bite.friend.manager.MessageCacheManager;
import com.bite.friend.mapper.message.MessageMapper;
import com.bite.friend.mapper.message.MessageTextMapper;
import com.bite.friend.service.user.UserMessageService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserMessageServiceImpl implements UserMessageService {


    @Autowired
    private MessageCacheManager messageCacheManager;

    @Autowired
    private MessageTextMapper messageTextMapper;

    @Autowired
    private MessageMapper messageMapper;

    @Override
    public TableDataInfo list(PageQueryDTO dto) {
        //展示消息列表-模仿用户竞赛列表
        Long userId = ThreadLocalUtil.get(Constants.USER_ID,Long.class);
        Long total = messageCacheManager.getListSize(userId);
        List<MessageTextVO> messageTextVOList;
        if (total == null || total <=0){
            //没数据,从数据库拿 并且同步
            //从哪个库查 还要通过竞赛id查询竞赛基本信息
            PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
            messageTextVOList = messageTextMapper.selectUserMsgList(userId);

            messageCacheManager.refreshCache(userId);
            total = new PageInfo<>(messageTextVOList).getTotal();
        }else {
            //redis有数据
            messageTextVOList = messageCacheManager.getMsgTextVOList(dto,userId);
            //total拿去方式不一样
            //因为可能redis异常,又重新刷新了
        }
        if (CollectionUtil.isEmpty(messageTextVOList)){
            return TableDataInfo.empty();
        }
        return TableDataInfo.success(messageTextVOList,total);
    }
}
